package com.ruoyi.web.controller.system;

import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.constant.CommonConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.web.entity.SysRunLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * description: 系统运行日志管理控制层
 * date: 2023年11月23日 16:44
 * author: tmac-1
 * version: 1.0
 */
@RestController
@RequestMapping("/system/run/log")
@Slf4j
public class SysRunLogController {

    @Value("${ruoyi.runLogFile}")
    private String fileDirectory;
    List<SysRunLog> runLogList = new ArrayList<>();


    /**
     * 获取运行日志列表
     *
     * @return
     */
    @GetMapping("/getRunLogList")
    public AjaxResult getRunLogList() {
        runLogList.removeAll(runLogList);
        long level = 0L;
        List<SysRunLog> fileList = getRunLogFile(fileDirectory, 1L, level);
        return AjaxResult.success(fileList);
    }

    private List<SysRunLog> getRunLogFile(String path, long id, long pid) {
        File file = new File(path);
        if (file.exists()) {
            File[] array = file.listFiles();
            List fileList = Arrays.asList(array);
            //对读到的本地文件夹进行排序
            Collections.sort(fileList, new Comparator<File>() {
                @Override
                public int compare(File o1, File o2) {
                    if (o1.isDirectory() && o2.isFile()) {
                        return -1;
                    }
                    if (o1.isFile() && o2.isDirectory()) {
                        return 1;
                    }
                    return o1.lastModified() > o2.lastModified() ? -1 : 1;
                }
            });

            for (int i = 0; i < array.length; i++) {
                File arrayFile = array[i];
                SysRunLog runLog = new SysRunLog();
                runLog.setParentNodeId(pid);
                runLog.setNodeId(id);
                runLog.setNodeName(arrayFile.getName());
                String fileSize = new BigDecimal(String.valueOf(arrayFile.length()))
                        .divide(new BigDecimal("1048576"), 2, BigDecimal.ROUND_HALF_UP) + "MB";
                runLog.setFileSize(fileSize);
                runLog.setUpdateTime(DateUtil.date(arrayFile.lastModified()));
                runLog.setDownLoadPath(file.getPath().replaceAll("\\\\", "/") + "/" + arrayFile.getName());
                //判断是否为文件夹，是的话进行递归
                if (arrayFile.isDirectory()) {
                    runLog.setIsDirectory(CommonConstants.STR_Y);
                    runLogList.add(runLog);
                    //进行递归，此时的pid为上一级的id
                    getRunLogFile(arrayFile.getPath(), id * 10 + 1, id);
                    id++;
                } else {
                    runLogList.add(runLog);
                    id++;
                }
            }
        }
        return runLogList;
    }

    /**
     * 下载运行日志
     *
     * @param runLog
     */
    @PostMapping("/download")
    public void download(SysRunLog runLog, HttpServletResponse response) throws Exception {
        String fileName = runLog.getNodeName();
        String filePath = runLog.getDownLoadPath();
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setContentLength((int) new File(filePath).length());
        FileUtils.setAttachmentResponseHeader(response, fileName);
        FileUtils.writeBytes(filePath, response.getOutputStream());
    }
}
